import React from 'react'
import { FlatList, Text, View, TouchableOpacity } from 'react-native'
import { Actions } from 'react-native-router-flux'
import { Container, Header, Item, Input, Icon, Button } from 'native-base'
import { connect } from 'react-redux' // 引入connect函数
import ItemImage from '../../components/list/articleItem'
import Page from '../../libs/page'
import ListEmpty from '../../components/listEmpty'
import commonStyle from '../../libs/commonStyle'
import Iconfont from '../../components/iconfont'

const ITEM_HEIGHT = 100

const apiUrl = '/api/article/list'
class List extends React.Component {
  constructor () {
    super()
    this.state = {
      keyValue: '',
      pageManager: {},
      list: [],
			isComplete: false,
      refreshing: false
    }
  }

  _onBack () {
    Actions.pop()
  }

  // 加载更多
  async _onEndReached () {
		if (this.state.isComplete) return
		let list = await this.state.pageManager.next()
		if (!list || !list.length) {
			this.state.isComplete = true
			this.state.list.push({
				type: 'complete'
			})
		}
    list && this.setState({
      list
    })
  }

  renderItem = ({ item }) => {
		if (item.type === 'complete') {
			return this.renderBoundaryItem('没有更多数据了')
		}
		if (item.type === 'empty') {
			return this.renderBoundaryItem('未找到相关内容')
		}
    return (
      <ItemImage
        key={item.id}
        info={item}
        money={this.props.curTypeItem.money}
      />
    )
  }

  async _onRefresh () {
    let list = await this.state.pageManager.start()
    this.setState({
      list,
			isComplete: false
    })
  }

  async onSearch () {
    let key = this.state.keyValue
    if (!key) return
    let apiUrl = '/api/article/listByName'
    // 查询文章列表
    let pageManager = new Page({
      httpMethod: 'get',
      apiUrl,
      // TODO data.data?
      dataKey: 'data.data.list',
      params: {
        name: key
      }
    })
		let isComplete = false
    let list = await pageManager.start()
		if (!list || !list.length) {
			list = [{
				type: 'empty'
			}]
			isComplete = true
		}
    this.setState({
      pageManager,
			isComplete,
      list
    })
  }

	renderBoundaryItem(info) {
		return (
			<View style={[commonStyle.h300, commonStyle.flexVerticalCenter, commonStyle.pt30]}>
				<Text style={[commonStyle.colorGray, commonStyle.f24]}>{info}</Text>
			</View>
		)
	}
  render () {
    return (
      <Container>
        <Header
          searchBar
          rounded
          style={{ backgroundColor: '#f5f5f5', position: 'relative' }}
        >
          <TouchableOpacity
            activeOpacity={1}
            onPress={this._onBack}
            style={[commonStyle.w50, commonStyle.h100, commonStyle.flexCenter]}
          >
            <Iconfont
              name='left_line'
              style={[commonStyle.f40, commonStyle.colorBlackLight]}
            />
          </TouchableOpacity>
          <Item>
            <View style={[commonStyle.flexCenter, commonStyle.flexRow]}>
              <Icon name='ios-search' />
              <Input
                placeholder='请输入文章标题关键字'
                style={{ fontSize: 12 }}
                onChangeText={val => {
                  this.setState({
                    keyValue: val
                  })
                }}
              />

              <Button transparent onPress={this.onSearch.bind(this)}>
                <Text
                  style={[
                    commonStyle.activeColor,
                    commonStyle.f30,
                    commonStyle.pr40
                  ]}
                >
                  搜索
                </Text>
              </Button>
            </View>
          </Item>
        </Header>
        <FlatList
          data={this.state.list}
          renderItem={this.renderItem}
          keyExtractor={item => item.name}
          refreshing={this.state.refreshing}
          onRefresh={this._onRefresh.bind(this)}
          onEndReachedThreshold={0.1}
          onEndReached={this._onEndReached.bind(this)}
          getItemLayout={(data, index) => ({
            length: ITEM_HEIGHT,
            offset: (ITEM_HEIGHT + 2) * index,
            index
          })}
        />
      </Container>
    )
  }
}

export default connect(state => ({
  curTypeItem: state.article.curTypeItem
}))(List)
